"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : Compatibility
Case Name   : 当前用户为superuser，set password修改密码
Create At   : 2022/08/15
@zou_jialiang0501162243
Description :
        1.创建用户和兼容B库
        2.set password不指定用户
        3.set password指定当前用户
        4.set password指定系统管理员用户
        5.set password指定有create role权限的用户
        6.set password指定无create role权限的用户
        7.set password指定不存在的用户
Expect      :
        1.创建成功
        2.修改成功
        3.修改成功
        4.修改成功
        5.修改成功
        6.修改成功
        7.报错
History     :
    modified by @zou_jialiang050,2023.03.21，修改guc参数设置命令，删除single=TRUE选项
    modified by @zou_jialiang050,2023.03.28，修改断言信息确保Degraded断言成功
"""
import os
import time
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class ClientConnection(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.common = Common()
        self.constant = Constant()
        self.sh_primary = CommonSH('PrimaryDbUser')
        self.us_name1 = 'us_setpassword0001_01'
        self.us_name2 = 'us_setpassword0001_02'
        self.us_name3 = 'us_setpassword0001_03'
        self.us_name4 = 'us_setpassword0001_04'
        self.passwd1 = 'qwertyuiop'
        self.passwd2 = 'abcdefg'
        self.db_name = 'db_setpassword0001'
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        text1 = '--------修改密码复杂度策略   expect:修改成功--------'
        self.log.info(text1)
        self.pwd_1 = self.common.show_param('password_policy')
        res1 = self.sh_primary.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             'password_policy=0')
        self.log.info(res1)
        self.assertTrue(res1, '执行失败' + text1)
        text2 = '--------修改可重用天数为0   expect:修改成功--------'
        self.log.info(text2)
        self.pwd_2 = self.common.show_param('password_reuse_time')
        res2 = self.sh_primary.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             'password_reuse_time=0')
        self.log.info(res2)
        self.assertTrue(res2, '执行失败' + text2)
        text3 = '--------重启数据库   expect:重启成功--------'
        self.log.info(text3)
        res3 = self.sh_primary.restart_db_cluster()
        self.log.info(res3)
        status = self.sh_primary.get_db_cluster_status()
        self.assertTrue("Degraded" in status or "Normal" in status,
                        '执行失败' + text3)

    def test_set_password(self):
        text = '--------step1:创建用户和兼容B库   expect:创建成功--------'
        self.log.info(text)
        create_us1 = f"drop user if exists {self.us_name1};" \
                     f"create user {self.us_name1} password '{self.passwd1}';"
        create_us2 = f"drop user if exists {self.us_name2};" \
                     f"create user {self.us_name2} password '{self.passwd1}';"
        create_us3 = f"drop user if exists {self.us_name3};" \
                     f"create user {self.us_name3} password '{self.passwd1}';"
        alter_us = f"grant all privileges to {self.us_name1};" \
                   f"alter user {self.us_name2} createrole;"
        res1 = self.sh_primary.execut_db_sql(sql=create_us1)
        self.log.info(res1)
        self.assertIn(self.constant.CREATE_ROLE_SUCCESS_MSG, res1,
                      '执行失败' + text)
        res2 = self.sh_primary.execut_db_sql(sql=create_us2)
        self.log.info(res2)
        self.assertIn(self.constant.CREATE_ROLE_SUCCESS_MSG, res2,
                      '执行失败' + text)
        res3 = self.sh_primary.execut_db_sql(sql=create_us3)
        self.log.info(res3)
        self.assertIn(self.constant.CREATE_ROLE_SUCCESS_MSG, res3,
                      '执行失败' + text)
        res4 = self.sh_primary.execut_db_sql(sql=alter_us)
        self.log.info(res4)
        for info in res4.splitlines():
            self.assertEqual(self.constant.ALTER_ROLE_SUCCESS_MSG, info,
                             '执行失败' + text)
        create_db = f"drop database if exists {self.db_name};" \
                    f"create database {self.db_name} dbcompatibility='B';" \
                    f"\c {self.db_name}"
        res5 = self.sh_primary.execut_db_sql(create_db)
        self.log.info(res5)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, res5,
                      '执行失败' + text)
        msg = f'You are now connected to database "{self.db_name}"'
        self.assertIn(msg, res5, '执行失败' + text)

        text = '--------step2:当前用户为superuser，set password不指定用户   ' \
               'expect:修改成功--------'
        self.log.info(text)
        sql_cmd1 = f"set password = '{self.passwd2}';"
        msg1 = self.sh_primary.execut_db_sql(sql_cmd1, dbname=self.db_name)
        self.log.info(msg1)
        self.assertEqual(self.constant.ALTER_ROLE_SUCCESS_MSG, msg1,
                         '执行失败' + text)

        text = '--------step3:当前用户为superuser，set password指定' \
               '连接用户   EXPECT:修改成功--------'
        self.log.info(text)
        sql_cmd2 = f"set password for {self.sh_primary.node.db_user} = " \
                   f"'{self.passwd1}';"
        msg2 = self.sh_primary.execut_db_sql(sql_cmd2, dbname=self.db_name)
        self.log.info(msg2)
        self.assertEqual(self.constant.ALTER_ROLE_SUCCESS_MSG, msg2,
                         '执行失败' + text)

        text = '--------step4:当前用户为superuser，set password指定' \
               '系统管理员用户     expect:修改成功--------'
        self.log.info(text)
        sql_cmd3 = f"set password for {self.us_name1} = '{self.passwd2}';"
        msg3 = self.sh_primary.execut_db_sql(sql_cmd3, dbname=self.db_name)
        self.log.info(msg3)
        self.assertEqual(self.constant.ALTER_ROLE_SUCCESS_MSG, msg3,
                         '执行失败' + text)

        text = '--------step5:当前用户为superuser，set password指定有' \
               'create role权限的用户   expect:修改成功--------'
        self.log.info(text)
        sql_cmd4 = f"set password for {self.us_name2} = '{self.passwd2}';"
        msg4 = self.sh_primary.execut_db_sql(sql_cmd4, dbname=self.db_name)
        self.log.info(msg4)
        self.assertEqual(self.constant.ALTER_ROLE_SUCCESS_MSG, msg4,
                         '执行失败' + text)

        text = '--------step6:当前用户为superuser，set password指定无create role' \
               '权限的用户   expect:修改成功--------'
        self.log.info(text)
        sql_cmd5 = f"set password for {self.us_name3} = '{self.passwd2}';"
        msg5 = self.sh_primary.execut_db_sql(sql_cmd5, dbname=self.db_name)
        self.log.info(msg5)
        self.assertEqual(self.constant.ALTER_ROLE_SUCCESS_MSG, msg5,
                         '执行失败' + text)

        text = '--------step7:当前用户为superuser，set password指定不存在的用户' \
               '   expect:报错--------'
        self.log.info(text)
        sql_cmd6 = f"set password for {self.us_name4} = '{self.passwd2}';"
        msg6 = self.sh_primary.execut_db_sql(sql_cmd6, dbname=self.db_name)
        self.log.info(msg6)
        einfo = f'ERROR:  role "{self.us_name4}" does not exist'
        self.assertEqual(einfo, msg6, '执行失败' + text)

    def tearDown(self):
        self.log.info('-----清理环境-----')
        text1 = '--------恢复初始用户密码   expect:修改成功--------'
        self.log.info(text1)
        alter_cmd = f"set password for {self.sh_primary.node.db_user} = " \
                    f"'{self.sh_primary.node.db_password}';"
        res1 = self.sh_primary.execut_db_sql(alter_cmd, dbname=self.db_name)
        self.log.info(res1)
        text2 = '--------删除用户和兼容B库   expect:删除成功--------'
        self.log.info(text2)
        drop_cmd = f"drop user if exists {self.us_name1};" \
                   f"drop user if exists {self.us_name2};" \
                   f"drop user if exists {self.us_name3};"
        res = self.sh_primary.execut_db_sql(drop_cmd)
        self.log.info(res)
        res0 = self.sh_primary.execut_db_sql(f"drop database if exists "
                                             f"{self.db_name};")
        self.log.info(res0)
        text3 = '--------恢复默认密码复杂度策略   expect:修改成功--------'
        self.log.info(text3)
        res2 = self.sh_primary.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f'password_policy = {self.pwd_1}')
        self.log.info(res2)
        text4 = '--------恢复默认可重用天数   expect:修改成功--------'
        self.log.info(text4)
        res3 = self.sh_primary.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f'password_reuse_time = '
                                             f'{self.pwd_2}')
        self.log.info(res3)
        text5 = '--------重启数据库   expect:重启成功--------'
        self.log.info(text5)
        res4 = self.sh_primary.restart_db_cluster()
        self.log.info(res4)
        status = self.sh_primary.get_db_cluster_status()
        self.assertEqual(self.constant.ALTER_ROLE_SUCCESS_MSG, res1,
                         '执行失败' + text1)
        for info in res.splitlines():
            self.assertEqual(self.constant.DROP_ROLE_SUCCESS_MSG, info,
                             '执行失败' + text1)
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, res0,
                      '执行失败' + text2)
        self.assertTrue(res2, '执行失败' + text3)
        self.assertTrue(res3, '执行失败' + text4)
        self.assertTrue("Degraded" in status or "Normal" in status,
                        '执行失败' + text5)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
